﻿<%@ WebHandler Language="C#" Class="ThumbnailHandler" %>
using System;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Caching;
using System.Configuration;

public class ThumbnailHandler : IHttpHandler
{
  //  ----- Copyright Philipos Sakellaropoulos 2002 -------
    Image _img;
    ImageResize _ImageResize = new ImageResize();
    int _width, _height; String _path; 
    bool _bStretch,_bBevel,_bUseCOMobject;
  
   public void ProcessRequest (HttpContext context)
   {
       try
       {
           string s =context.Request["u"];
           string[] list = s.Split('.');
           _height = Convert.ToInt32(list[list.Length - 1]);
           _width = Convert.ToInt32(list[list.Length - 2]);
           _path = "/" + s.Substring(0, s.Length - _height.ToString().Length - _width.ToString().Length - 2);
           _path = context.Request.MapPath(_path);
       }
       catch
       {
           _width = 150;
           _height = 150;
           _path = "../images/no_image.jpg";
       }
       try
       {
           String sCacheKey;
           bool bFoundInCache = true; // by default
           // create our COM thumbnail generator
           // allow stretch of thumbnails
           _bStretch = (context.Request["AllowStretch"] == "true");
           // bevel thumbnails
           _bBevel = (context.Request["Bevel"] == "true");
           _bUseCOMobject = (context.Request["UseCOMobj"] == "true");
           // put parameters for thumbnail requested


           // get a reference to the cache object
           Cache MyCache = context.Cache;
           sCacheKey = _ImageResize.GetUniqueThumbName(_path, _width, _height);
           // --- remove from cache when we want to refresh
           bool bRefresh = (context.Request["Refresh"] == "true");
           if (bRefresh)
           {
               MyCache.Remove(sCacheKey);
           }
           if (MyCache[sCacheKey] == null)
           {
               // the thumbnail does not exist in cache, create it...
               // Create a bitmap of the thumbnail and show it
               //      bitmap = _oGenerator.ExtractThumbnail();    //chỗ này tự khóa
               _img = Image.FromFile(_path);
               _img = _ImageResize.Crop(_img, _width, _height, ImageResize.AnchorPosition.Center);
               bFoundInCache = false;
           }
           else
           { // bitmap is in cache
               _img = (Image)MyCache[sCacheKey];
           }
           context.Response.ContentType = "image/Jpeg";
           _img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
           //if(bFoundInCache) LogMessage("Found in cache");
           // else LogMessage("NOT Found in cache");
           //cache thumbnail, make it dependent upon the file and thumbnail size
           if (!bFoundInCache)
           {
               CacheDependency dependency = new CacheDependency(_path);
               int mins;
               mins = 20;
               //try
               //{
               //    mins = int.Parse(ConfigurationSettings.AppSettings["SlidingExpireMinutes"]);
               //}
               //catch (ArgumentNullException ex) 
               //{ 
               //    mins = 20; 
               //}
               MyCache.Insert(sCacheKey, _img, dependency,
                  Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(mins),
                  CacheItemPriority.Default, new CacheItemRemovedCallback(RemovedCallback));
               dependency.Dispose();
           }
           // bitmap in cache, dont dispose yet
           //bitmap.Dispose ();
       }
       catch
       {
       }
   }

   static public void RemovedCallback(String k, Object item, CacheItemRemovedReason r)
   {
       ((Bitmap)item).Dispose();
       //LogMessage("Callback");
   }

   // for custom tracing, normal tracing does not work with WebHandlers
   static void LogMessage(String mess)
   {
       StreamWriter sw = new StreamWriter("c:\\ASP.NET_log.txt", true);
       sw.WriteLine(mess);
       sw.Close();
   }

   public bool IsReusable
   {
       get { return true; }
   }

}
